#ifndef DATABASE_H
#define DATABASE_H

#include <QtSql>
#include <Maestro/mcplugins.h>

/**
  * Used to protect the database from direct queries by plugins for security.
  * Also provides convenient methods for retrieving information.
  */

class Querier
{
    public:
        /**
          * Allows the Querier to use this class without having to use pointers.
          */
        Querier() {

        }

    private:
        static QSqlDatabase database; //the database to use
    public:

        /**
          * Creates a database querier which access the given database
          *
          * @param the database for the querier to use
          */
        Querier(QSqlDatabase db) {
            database=db;
        }

        static void setDatabase(QSqlDatabase db) {
            database=db;
        }

        //this is just for testing
        static QSqlQuery getResult(QString input) {
            return QSqlQuery(input,database);
        }

        static QSqlQueryModel * getModel(QString input) {
            QSqlQueryModel * model =new QSqlQueryModel;
            model->setQuery(input,database);
            while (model->canFetchMore())
                 model->fetchMore();
            return model;
        }

        static long long addMediaFile(MediaFile * file, QString subdirectory="") {
            QString x="SELECT * FROM MediaFiles WHERE folderID='";
            x+=('0'+file->folderID);
            x+="' AND fileName='"+file->shortName.replace("'","''")+"'";
            QSqlQueryModel * result=getModel(x);
            //qDebug() <<result->rowCount();
            if(result->rowCount()==0) {
                QFileInfo fileInfo=QFileInfo(file->shortName);
                QSqlQueryModel * typeSearch=getModel("SELECT * FROM Extensions WHERE extension='."+fileInfo.suffix().toLower()+"'");
                if(typeSearch->rowCount()==0) {
                    return -1;
                }
                QString q="INSERT INTO MediaFiles (folderID, fileName, fileType, subdirectory) VALUES('";
                q+=QString::number(file->folderID);
                q+="','";
                q+=file->shortName;
                q+="','"+typeSearch->record(0).value("fileType").toString();
                q+="','"+subdirectory;
                q+="')";
                //qDebug() <<q;
                QSqlQuery query=getResult(q);
                //qDebug() <<file<<" "<<query.lastInsertId();
                file->mediaID=query.lastInsertId().toLongLong();
                return query.lastInsertId().toLongLong();
            } else {
                getResult("UPDATE MediaFiles SET subdirectory='"+subdirectory+"' WHERE mediaID='"+result->record(0).value("mediaID").toString()+"'");
            }
            return result->record(0).value("mediaID").toLongLong();
        }

        static QList<MediaFile *> * getFilesOfType(QString type, QString filter) {
           QList<MediaFile *> * files= new QList<MediaFile *>();
            QString query="SELECT * FROM MediaFiles mf INNER JOIN ListenedFolders lf ON lf.folderID=mf.folderID WHERE mf.accessible='1' AND mf.fileType LIKE '%"+type+"%'";
            if(filter.size()>0) {
                query+=" AND "+filter;
            }
            QSqlQueryModel * model= Querier::getModel(query);
            for(int i=0; i<model->rowCount(); i++) {
                MediaFile * file=new MediaFile();

                QString path=model->record(i).value("path").toString();
                QString subdirectory=model->record(i).value("subdirectory").toString();
                if(subdirectory.size()>0) {
                    path+=subdirectory;
                }
                QDir directory=QDir(path);
                //qDebug()<<path;
                if(path.startsWith(".")) {
                    directory=QDir(qApp->applicationDirPath());
                    #if defined(Q_OS_WIN)
                        if (directory.dirName().toLower() == "debug" || directory.dirName().toLower() == "release")
                            directory.cdUp();
                    #elif defined(Q_OS_MACA)
                            directory.cdUp();
                            directory.cdUp();
                            directory.cdUp();
                    #endif
                    //qDebug()<<directory.absoluteFilePath(".");

                    int start=path.indexOf("/");
                    path=path.mid(start+1);

                    directory.cd(path);
                    //folder->path=directory.absoluteFilePath("");
                }
                //qDebug()<<"directory "<<directory.absolutePath();
                file->mediaID=model->record(i).value("mediaID").toInt();
                file->shortName=model->record(i).value("fileName").toString();
                file->fileLocation=directory.absolutePath();
                file->description=model->record(i).value("description").toString();
                file->artist=model->record(i).value("artist").toString();
                file->title=model->record(i).value("title").toString();
                file->coverArt=model->record(i).value("coverArt").toString();
                files->append(file);
            }
            return files;
        }

        static void updateMediaFile(MediaFile * file) {
            //qDebug()<<"UPDATE MediaFiles SET artist='"+file->artist+"', title='"+file->title+"', description='"+file->description+"' WHERE mediaID='"+QString::number(file->mediaID)+"'";
            getResult("UPDATE MediaFiles SET artist='"+file->artist+"', title='"+file->title+"', description='"+file->description+"', coverArt='"+file->coverArt+"' WHERE mediaID='"+QString::number(file->mediaID)+"'");
            //getResult("UPDATE MediaFiles SET artist='"+file->artist+"', title='"+file->title+"', description='"+file->description+"' WHERE mediaID='"+QString::number(file->mediaID)+"'");
        }
};

#endif // DATABASE_H

